/*
 * Ganesa Copyright (C) 2008 Wim Crols <twimpiex@gnx.be>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package be.gnx.ganesa.application.command;

import java.util.Collection;
import java.util.Vector;

import be.gnx.ganesa.application.event.CommandStackEvent;
import be.gnx.ganesa.application.event.CommandStackListener;

public class CommandStack {

  private Vector<Command> commands = new Vector<Command>();

  private int numberOfAppliedCommands = 0;

  private void reduce() {
    while (commands.size() > numberOfAppliedCommands) {
      commands.remove(numberOfAppliedCommands);
    }
  }

  public boolean add(Command command) {
    reduce();
    boolean returnValue = commands.add(command);
    numberOfAppliedCommands++;
    fireEvent(commandStackListeners);
    return returnValue;
  }

  public boolean addAll(Collection<? extends Command> commands) {
    reduce();
    boolean returnValue = this.commands.addAll(commands);
    numberOfAppliedCommands += commands.size();
    fireEvent(commandStackListeners);
    return returnValue;
  }

  public void clear() {
    commands.clear();
    numberOfAppliedCommands = 0;
    fireEvent(commandStackListeners);
  }

  public Vector<Command> getCommands() {
    return commands;
  }

  /* event listeners */
  private Vector<CommandStackListener> commandStackListeners = new Vector<CommandStackListener>();

  private void fireEvent(Vector<CommandStackListener> commandStackListeners) {
    for (CommandStackListener commandStackListener : commandStackListeners) {
      commandStackListener.commandStackEventhappened(new CommandStackEvent(this));
    }
  }

  public void addCommandStackListener(CommandStackListener commandStackListener) {
    if (commandStackListener == null) {
      throw new NullPointerException();
    } else {
      commandStackListeners.add(commandStackListener);
    }
  }

  public void removeCommandStackListener(CommandStackListener commandStackListener) {
    if (commandStackListener == null) {
      throw new NullPointerException();
    } else {
      commandStackListeners.remove(commandStackListener);
    }
  }

}
